from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import logging
from dbserver import DBManager


# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__)

# 初始化数据库连接
db = DBManager()

# 配置CORS
CORS(app, resources={r"/*": {"origins": "*"}})

# 错误处理
@app.errorhandler(Exception)
def handle_error(error):
    logger.error(f"Error occurred: {str(error)}")
    return jsonify({
        "error": str(error),
        "status": "error"
    }), 500

# 示例路由
@app.route('/api/chat', methods=['POST'])
def chat():
    try:
        data = request.get_json()
        model = data.get('model', 'mistral:latest')
        messages = data.get('messages', [])
        
        # 这里可以添加与Ollama的交互逻辑
        # 目前返回模拟数据
        response = {
            "model": model,
            "response": "这是一个示例响应",
            "status": "success"
        }
        
        return jsonify(response)
    except Exception as e:
        logger.error(f"Chat endpoint error: {str(e)}")
        raise

# 健康检查路由
@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({"status": "healthy"})

# 获取历史会话列表
@app.route('/api/history', methods=['GET'])
def get_history():
    try:
        # 使用DBManager的select方法查询历史记录
        history_records = db.select(
            table='t_chat_history',
            fields='id, session_id, title, create_time',
            order_by='create_time DESC'
        )
        
        # 格式化返回数据
        history = [{
            'id': record['id'],
            'session_id': record['session_id'],
            'title': record['title'],
            'create_time': record['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        } for record in history_records]
        
        return jsonify(history)
    except Exception as e:
        logger.error(f"Failed to fetch chat history: {str(e)}")
        raise

# 保存会话内容列表
# Save chat session content
@app.route('/api/save_messages', methods=['POST'])
def save_messages():
    try:
        data = request.get_json()
        logger.info(f"收到会话内容参数：${data}")
        messages = data.get('messages', [])
        
        # Validate input data
        if not isinstance(messages, list):
            return jsonify({
                "error": "Invalid input format - messages must be a list",
                "status": "error"
            }), 400
            
        # Insert each message into database
        for message in messages:
            session_id = message.get('session_id')
            role = message.get('role')
            content = message.get('content')
            
            if not all([session_id, role, content]):
                return jsonify({
                    "error": "Missing required fields",
                    "status": "error"
                }), 400
                
            db.insert(
                table='t_chat_messages',
                data={
                    'session_id': session_id,
                    'role': role,
                    'content': content
                }
            )
        
        return jsonify({
            "status": "success",
            "message": f"Successfully saved {len(messages)} messages"
        })
        
    except Exception as e:
        logger.error(f"Failed to save chat messages: {str(e)}")
        raise

# 根据会话ID获取消息列表
# Get messages by session ID
@app.route('/api/messages/<session_id>', methods=['GET'])
def get_messages(session_id):
    try:
        # Validate session_id
        if not session_id:
            return jsonify({
                "error": "Session ID is required",
                "status": "error"
            }), 400
            
        # Query messages from database
        messages = db.select(
            table='t_chat_messages',
            fields='role, content, create_time',
            condition={'session_id': session_id},
            order_by='create_time ASC'
        )
        
        # Format response data
        formatted_messages = [{
            'role': msg['role'],
            'content': msg['content'],
            'create_time': msg['create_time'].strftime('%Y-%m-%d %H:%M:%S')
        } for msg in messages]
        
        return jsonify({
            "status": "success",
            "messages": formatted_messages
        })
        
    except Exception as e:
        logger.error(f"Failed to fetch messages for session {session_id}: {str(e)}")
        raise

# 保存会话列表
# Save chat session information
@app.route('/api/save_session', methods=['GET'])
def save_session():
    try:
        # Get parameters from URL query string instead of JSON body
        session_id = request.args.get('session_id')
        title = request.args.get('title')
        
        # Validate input data
        if not session_id or not title:
            return jsonify({
                "error": "Session ID and title are required",
                "status": "error"
            }), 400
            
        # Insert session info into database
        db.insert(
            table='t_chat_history',
            data={
                'session_id': session_id,
                'title': title
            }
        )
        return jsonify({
            "status": "success",
            "message": "Successfully saved session information"
        })
        
    except Exception as e:
        logger.error(f"Failed to save session information: {str(e)}")
        raise


# 删除会话及其消息
@app.route('/api/delete_session/<session_id>', methods=['DELETE'])
def delete_session(session_id):
    try:
        # 验证session_id
        if not session_id:
            return jsonify({
                "error": "Session ID is required",
                "status": "error"
            }), 400
            
        # 首先删除该会话的所有消息
        db.delete(
            table='t_chat_messages',
            condition={'session_id': session_id}
        )
        
        # 然后删除会话记录
        db.delete(
            table='t_chat_history',
            condition={'session_id': session_id}
        )
        
        return jsonify({
            "status": "success",
            "message": f"Successfully deleted session {session_id} and its messages"
        })
        
    except Exception as e:
        logger.error(f"Failed to delete session {session_id}: {str(e)}")
        raise


def generate_speech(text, voice="tts_models/zh-CN/baker/tacotron2-DDC"):
    try:
        # 文本预处理：去除特殊字符，限制长度
        import re
        max_length = 500
        text = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', str(text))[:max_length]
        
        # 分句处理
        sentences = re.split(r'[。！？]', text)
        sentences = [s.strip() for s in sentences if s.strip()]
        
        tts = TTS(model_name=voice)
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
            temp_path = tmp_file.name
            for sentence in sentences:
                tts.tts_to_file(text=sentence, file_path=temp_path)
            return temp_path
    except Exception as e:
        logger.error(f"TTS generation failed: {str(e)}\nText: {text}\nVoice: {voice}")
        raise



if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)